package internal

import (
	"fmt"
	"strings"

	"v8s-api/rest-api/target/generated-sources"
	gen_devprofile "v8s-sm-proxy/rest/target/generated-sources/devprofile"
)

type (
	ResourceName struct {
		Partition  string
		Service    string
		Region     string
		AccountID  ProjectID
		ProjectID  string
		ResourceID string
	}

	ProjectID string
	TaskID    string
)

func ParseResourceNameFromV8SAPI(name generated.ResourceName) (ResourceName, error) {
	return ParseResourceName(string(name))
}

func ParseResourceNameFromDevelopersProfileAPI(name gen_devprofile.ResourceName) (ResourceName, error) {
	return ParseResourceName(string(name))
}

func ParseResourceName(str string) (ResourceName, error) {
	split := strings.Split(str, ":")
	if len(split) < 7 {
		return ResourceName{}, fmt.Errorf("expected 7 parts with delimeter ':', but was '%d'", len(split))
	}

	return ResourceName{
		Partition:  split[1],
		Service:    split[2],
		Region:     split[3],
		AccountID:  ProjectID(split[4]),
		ProjectID:  split[5],
		ResourceID: split[6],
	}, nil
}

func (rn ResourceName) ToV8SApi() generated.ResourceName {
	return generated.ResourceName(rn.String())
}

func (rn ResourceName) ToDeveloperProfilesAPI() gen_devprofile.ResourceName {
	return gen_devprofile.ResourceName(rn.String())
}

func (rn ResourceName) String() string {
	return fmt.Sprintf("rn:%s:%s:%s:%s:%s:%s", rn.Partition, rn.Service, rn.Region, rn.AccountID, rn.ProjectID, rn.ResourceID)
}

func (id ProjectID) ToV8SProjectID() generated.ProjectId {
	return generated.ProjectId(id)
}
